class RoutersHash {
	constructor() {
		this.routers = {};
		this.currentUrl = {};
		this.history = [];
		this.currentIndex = this.history.length - 1;
		window.addEventListener("load", this.refresh.bind(this), false);
		window.addEventListener("hashchange", this.refresh.bind(this), false);
	}
	router(path, callback) {
		this.routers[path] = callback || function() {};
	}
	refresh() {
		this.currentUrl = location.hash.slice(1) || "/";
		this.routers[this.currentUrl]();
		this.history.push(this.currentUrl);
		this.currentIndex = this.history.length - 1;
	}
	backoff() {
		this.currentIndex <= 0 ?
			(this.currentIndex = 0) :
			(this.currentIndex = this.currentIndex - 1);
		location.hash = `#${this.history[this.currentIndex]}`
		this.routers[this.history[this.currentIndex]]();
	}
};

//基于history
class Routers{
	constructor() {
	    this.routers = {};
		this._bindPopState();
	}
	init(path){
		history.replaceState({path:path},null,path);
		this.routers[path] && this.routers[path]();
	}
	router(path,callback){
		this.routers[path] = callback || function(){}; 
	}
	go(path){
		history.pushState({path:path},null,path);
		this.routers[path] && this.routers[path]();
	}
	_bindPopState(){
		window.addEventListener("popstate",e=>{
			const path= e.state && e.state.path;
			this.routers[path] && this.routers[path]();
		})
	}
}
